{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 1.准备数据",
   "id": "9a8e0b42781f6985"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-26T05:40:04.230622Z",
     "start_time": "2025-02-26T05:40:02.137887Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import numpy as np\n",
    "# 1.数据准备\n",
    "x_values = [i for i in range(1,11)]\n",
    "x_trains = np.array(x_values, dtype=np.float32)\n",
    "x_trains = x_trains.reshape(-1,1)\n",
    "y_trains = [2 * x + 1 for x in x_trains]\n",
    "y_trains = np.array(y_trains, dtype=np.float32)\n",
    "y_trains = y_trains.reshape(-1,1)\n",
    "print(x_trains,\"\\n===\\n\", y_trains)"
   ],
   "id": "e8ed044aa3633064",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1.]\n",
      " [ 2.]\n",
      " [ 3.]\n",
      " [ 4.]\n",
      " [ 5.]\n",
      " [ 6.]\n",
      " [ 7.]\n",
      " [ 8.]\n",
      " [ 9.]\n",
      " [10.]] \n",
      "===\n",
      " [[ 3.]\n",
      " [ 5.]\n",
      " [ 7.]\n",
      " [ 9.]\n",
      " [11.]\n",
      " [13.]\n",
      " [15.]\n",
      " [17.]\n",
      " [19.]\n",
      " [21.]]\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2.构建模型",
   "id": "b7397378f63b1b26"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-22T03:42:39.910290Z",
     "start_time": "2025-02-22T03:42:39.815971Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 构建模型\n",
    "class LinearRegression(nn.Module):\n",
    "    def __init__(self, in_dim, out_dim):\n",
    "        super(LinearRegression, self).__init__()\n",
    "        self.in_dim = in_dim\n",
    "        self.out_dim = out_dim\n",
    "        self.linear = nn.Linear(in_dim, out_dim)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        x = self.linear(x)\n",
    "        return x\n",
    "    \n",
    "# 创建模型\n",
    "in_dim = 1\n",
    "out_dim = 1\n",
    "model = LinearRegression(in_dim, out_dim)\n",
    "model"
   ],
   "id": "7c9bbcda02f42119",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LinearRegression(\n",
       "  (linear): Linear(in_features=1, out_features=1, bias=True)\n",
       ")"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 3.参数处理和损失函数",
   "id": "8f490cd54f4fd4fe"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-22T03:45:08.030963Z",
     "start_time": "2025-02-22T03:45:05.470838Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 参数处理和损失函数\n",
    "epochs = 1000\n",
    "learning_rate = 0.01\n",
    "loss_fn = nn.MSELoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n",
    "for epoch in range(epochs):\n",
    "    epoch += 1\n",
    "    # 训练数据\n",
    "    inputs = torch.from_numpy(x_trains).float()\n",
    "    labels = torch.from_numpy(y_trains).float()\n",
    "    outputs = model(inputs)\n",
    "    # 梯度清0\n",
    "    optimizer.zero_grad()\n",
    "    # 计算损失函数\n",
    "    loss = loss_fn(outputs, labels)\n",
    "    # 反向传播\n",
    "    loss.backward()\n",
    "    # 更新权重\n",
    "    optimizer.step()\n",
    "    if epoch % 100 == 0:\n",
    "        print(\"epoch: {}, loss: {}\".format(epoch, loss.item()))\n",
    "        "
   ],
   "id": "55855ecb2c9c18b4",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch: 100, loss: 2.6766324043273926\n",
      "epoch: 200, loss: 0.024363918229937553\n",
      "epoch: 300, loss: 0.009444705210626125\n",
      "epoch: 400, loss: 0.007805563509464264\n",
      "epoch: 500, loss: 0.0062505402602255344\n",
      "epoch: 600, loss: 0.004854497499763966\n",
      "epoch: 700, loss: 0.0036583333276212215\n",
      "epoch: 800, loss: 0.00267533166334033\n",
      "epoch: 900, loss: 0.0018980574095621705\n",
      "epoch: 1000, loss: 0.001305835205130279\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 4.评估",
   "id": "d225c5e99f7e2f1c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-22T03:50:48.003999Z",
     "start_time": "2025-02-22T03:50:47.992658Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 评估\n",
    "predicted = model(torch.from_numpy(x_trains).requires_grad_()).data.numpy()\n",
    "predicted"
   ],
   "id": "40cac34903e52626",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 3.0662525],\n",
       "       [ 5.0547633],\n",
       "       [ 7.043274 ],\n",
       "       [ 9.031785 ],\n",
       "       [11.020296 ],\n",
       "       [13.008806 ],\n",
       "       [14.997317 ],\n",
       "       [16.985828 ],\n",
       "       [18.974339 ],\n",
       "       [20.96285  ]], dtype=float32)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 6.模型保存和读取",
   "id": "1da60cdffee9491"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-22T03:52:53.837732Z",
     "start_time": "2025-02-22T03:52:53.828640Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 模型保存和读取\n",
    "torch.save(model.state_dict(), \"model.pth\")\n",
    "model.load_state_dict(torch.load(\"model.pth\",weights_only=False))"
   ],
   "id": "b37853a3fd57d49c",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 19
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
